package com.ruif.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.ruif.model.Car;
import com.ruif.util.StringUtil;

public class CarDAO
{
    
    /**
     * 查询 Car 表所有记录
     * @param conn
     * @return
     * @throws Exception
     */
    public ResultSet list(Connection conn, String licenseNo) throws Exception
    {
        StringBuffer sb = new StringBuffer("select * from t_car");
        if (!StringUtil.isEmpty(licenseNo))
        {
            sb.append(" and licenseNo like '%" + licenseNo + "%'");
        }
        PreparedStatement pst = conn.prepareStatement(sb.toString().replaceFirst("and", "where"));
        return pst.executeQuery();
    }
    
    /**
     * 新增 Car 表一条记录 
     * @return
     */
    public int add(Connection conn, Car car) throws Exception
    {
        String sql = "insert into t_car values(null, ?, ?, ?, ?, ?)";
        
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, car.getLicenseNo());
        stmt.setString(2, car.getPrice() + "");
        stmt.setString(3, car.getType());
        stmt.setString(4, car.getDate());
        stmt.setString(5, car.getDescrip());
        
        return stmt.executeUpdate();
    }
    
    /**
     * 修改一条记录
     * @param conn
     * @param car
     * @return
     * @throws Exception
     */
    public int modify(Connection conn, Car car) throws Exception
    {
        String sql = "update t_car set licenseNo=?,price=?,type=?,date=?,descrip=? where id=?";
        
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, car.getLicenseNo());
        stmt.setDouble(2, car.getPrice());
        stmt.setString(3, car.getType());
        stmt.setString(4, car.getDate());
        stmt.setString(5, car.getDescrip());
        stmt.setLong(6, car.getId());
        
        return stmt.executeUpdate();
    }
    
    /**
     * 删除一条记录
     * @param conn
     * @param id
     * @return
     * @throws Exception
     */
    public int delete(Connection conn, long id) throws Exception
    {
        String sql = "delete from t_car where id=?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setLong(1, id);
        return stmt.executeUpdate();
    }
    
    /**
     * 删除一条记录
     * @param conn
     * @param car
     * @return
     * @throws Exception
     */
    public int delete(Connection conn, Car car) throws Exception
    {
        return delete(conn, car.getId());
    }
    
}
